package edu.xpu.project.common.init;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import edu.xpu.project.common.utils.ConfigReader;
import edu.xpu.project.user.entity.ProjectUser;
import edu.xpu.project.user.service.ProjectUserService;

/**
 * @describe 在该类中可以初始化数据库数据
 * @author liukang
 * @date 2017年5月17日
 */
@Component
public class InitDatabase implements ApplicationListener<ContextRefreshedEvent> {
	
	@Autowired
	private ProjectUserService projectUserService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		//为数据库添加管理员用户(工号、密码)
		String sysPropertiesVal = "disable";
		try {
			sysPropertiesVal = ConfigReader.sysPropertiesVal("useAdmin");
		} catch (Exception e) {}
		String adminName = "admin";
		try {
			adminName = ConfigReader.sysPropertiesVal("adminName");
		} catch (Exception e) {}
		String adminPwd = "111111";
		try {
			adminPwd = ConfigReader.sysPropertiesVal("adminPwd");
		} catch (Exception e) {}
		//判断该用户是否存在
		ProjectUser userLogin = projectUserService.userLogin(adminName, adminPwd);
		if ("enable".equals(sysPropertiesVal)) {
			if (userLogin == null) {
				ProjectUser projectUser = new ProjectUser();
				projectUser.setName("管理员");
				projectUser.setCreateDate(new Date());
				projectUser.setUserNo(adminName);
				projectUser.setPwd(adminPwd);
				projectUser.setSex("1");
				projectUser.setUserType(3);
				//保存用户
				projectUserService.saveOrUpdate(projectUser);
			}
		} else if ("disable".equals(sysPropertiesVal)) {
			//删除用户
			if (userLogin != null) {
				projectUserService.delete(userLogin.getId());
			}
		}
		
	}

}
